package org.springside.modules.web.phaseListener.springsecuirty;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.aom.util.FaceUtil;
import org.springframework.security.AccountExpiredException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.concurrent.ConcurrentLoginException;
import org.springframework.security.ui.AbstractProcessingFilter;

public class LoginErrorPhaseListener implements PhaseListener {

	private static final long serialVersionUID = -7282061829850662922L;

	public void afterPhase(PhaseEvent arg0) {
	}

	public void beforePhase(final PhaseEvent arg0) {
		Exception e = (Exception) FacesContext
				.getCurrentInstance()
				.getExternalContext()
				.getSessionMap()
				.get(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
		if(e instanceof ConcurrentLoginException){
			FaceUtil.getSessionMap().put(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, e);
		}
		else if (e instanceof BadCredentialsException) {
			FaceUtil.getSessionMap().put(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, e);
        }else if (e instanceof AccountExpiredException) {
        	FaceUtil.getSessionMap().put(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, e);
		}
	}

	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

}
